import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:guji/common/utils.dart';
import 'package:guji/components/toast.dart';
import 'package:guji/global.dart';
import 'package:guji/manager/main_manager.dart';
import 'package:guji/pages/edit.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

class DetailPage extends StatefulWidget {
  DetailPage({Key key, this.id}) : super(key: key);
  final int id;
  @override
  State<StatefulWidget> createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  @override
  void initState() {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    super.initState();
  }

  var data;
  String formatted;
  GlobalKey globalKey = GlobalKey();

  Future<Uint8List> _capturePng() async {
    try {
      Future.delayed(Duration(milliseconds: 100), () async {
        RenderRepaintBoundary boundary =
            globalKey.currentContext.findRenderObject();
        var image = await boundary.toImage(pixelRatio: 3.0);
        ByteData byteData = await image.toByteData(format: ImageByteFormat.png);
        Uint8List pngBytes = byteData.buffer.asUint8List();
        final result = await ImageGallerySaver.saveImage(pngBytes,
            quality: 100, name: "网易云热评");
        Toast.show(context,
            msg: '图片保存${result['isSuccess'] ? "成功" : "失败"}', duration: 1);
      });
    } catch (e) {
      print(e);
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    MainManager _mainManager = Provider.of<MainManager>(context);

    _mainManager.query('select * from GUJI where id=${widget.id}').then(
      (value) {
        if (value.length > 0) {
          setState(() {
            data = value[0];
            var date = DateTime.fromMillisecondsSinceEpoch(data['id']);
            var formatter = new DateFormat('yyyy年M月d日');
            formatted = formatter.format(date);
          });
        }
      },
    );

    return data == null
        ? Scaffold(
            body: Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              color: Global.backgroundColor,
              child: Center(child: CircularProgressIndicator()),
            ),
          )
        : Scaffold(
            appBar: AppBar(
              iconTheme: IconThemeData(color: Global.primaryColor),
              backgroundColor: Global.backgroundColor,
              toolbarHeight: 50,
              elevation: 0,
              title: Text(
                formatted,
                style: TextStyle(
                  color: Global.fontSecondColor,
                  fontSize: 14,
                  fontFamily: 'FangZhengShuSongFanTi',
                  fontWeight: FontWeight.w600,
                ),
              ),
              actions: [
                InkWell(
                  onTap: () {
                    _capturePng();
                  },
                  child: Center(
                    child: Text(
                      '截图   ',
                      style: TextStyle(
                        color: Global.fontSecondColor,
                        fontSize: 18,
                        fontFamily: 'FangZhengShuSongFanTi',
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) =>
                            EditPage(id: widget.id, data: data),
                      ),
                    );
                  },
                  child: Center(
                    child: Text(
                      '编辑   ',
                      style: TextStyle(
                        color: Global.fontSecondColor,
                        fontSize: 18,
                        fontFamily: 'FangZhengShuSongFanTi',
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    Utils.showConfirmDialog(
                      context: context,
                      content: '确认删除？',
                      showCancelButton: true,
                      confirmCallback: () {
                        Navigator.of(context).pop();
                        _mainManager.delete(widget.id.toString());
                      },
                    );
                  },
                  child: Center(
                    child: Text(
                      '删除   ',
                      style: TextStyle(
                        color: Global.fontSecondColor,
                        fontSize: 18,
                        fontFamily: 'FangZhengShuSongFanTi',
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            body: Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              decoration: BoxDecoration(color: Global.backgroundColor),
              padding: EdgeInsets.all(20),
              child: SingleChildScrollView(
                child: RepaintBoundary(
                  key: globalKey,
                  child: Container(
                    padding: EdgeInsets.all(20),
                    decoration: BoxDecoration(color: Global.backgroundColor),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          data['title'],
                          style: TextStyle(
                            color: Global.fontColor,
                            fontSize: 25,
                            fontFamily: 'FangZhengShuSongFanTi',
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        SizedBox(height: 16),
                        Text(
                          data['data'],
                          style: TextStyle(
                            color: Global.fontColor,
                            fontSize: 18,
                            fontFamily: 'FangZhengShuSongFanTi',
                            fontWeight: FontWeight.w600,
                            height: 1.5,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          );
  }
}
